<template>
  <p-modal
    :title="title"
    :width="600"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <p-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <p-form :form="form">
        <p-row>
          <p-col :span="24">
            <p-form-item label="父级工序" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-tree-select
                @change="pidChange"
                tree-data-simple-mode
                v-decorator="[ 'pid', validatorRules.pid]"                 
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择父级工序"
                :load-data="onLoadData"
              />
            </p-form-item>
          </p-col>
          <p-col :span="12">
            <p-form-item label="工序编码" :labelCol="{span: 12}" :wrapperCol="{ span: 12}">
              <p-input
                v-decorator="[ 'processmcode', validatorRules.processmcode]"
                placeholder="请输入工序编码"
              ></p-input>
            </p-form-item>          
          </p-col>
          <p-col :span="12">
            <p-form-item label="工序名称" :labelCol="{span: 12}" :wrapperCol="{ span: 12}">
              <p-input
                v-decorator="[ 'processmname', validatorRules.processmname]"
                placeholder="请输入工序名称"
              ></p-input>
            </p-form-item>            
          </p-col>
          <p-col :span="24">
            <p-form-item label="工序描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input
                v-decorator="[ 'processsprc', validatorRules.processsprc]"
                placeholder="请输入工序描述"
              ></p-input>
            </p-form-item>
          </p-col>

          <p-col :span="24">
            <p-form-item label="工序层级" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input 
                disabled
                v-decorator="[ 'processlayer', validatorRules.processlayer]" 
              placeholder="请输工序层级"></p-input>
            </p-form-item>
          </p-col>
          <p-col :span="24" v-if="processlayer == 1">
            <p-form-item label="偏置期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input
                v-decorator="[ 'productoffset', validatorRules.productoffset]"
                placeholder="请输入偏置期"
              ></p-input>
            </p-form-item>
          </p-col>
          <p-col :span="24" v-if="processlayer == 2">
            <p-form-item label="工站物料是否合并" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-select v-decorator="[ 'distribution', validatorRules.distribution]">
                <p-select-option value=1>合并</p-select-option>
                <p-select-option value=2>不合并</p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
        </p-row>
      </p-form>
    </p-spin>
  </p-modal>
</template>

<script>
import pick from "lodash.pick";
import { FormTypes, getRefPromise } from "@/utils/JEditableTableUtil";
import { JEditableTableMixin } from "@/mixins/JEditableTableMixin";
import { validateDuplicateValue } from "@/utils/util";
import JDictSelectTag from "@/components/dict/JDictSelectTag";
import JTreeSelect from "@/components/mesCom/jeecg/MesBaPhhTreeSelect";
import MesPeProcessTreeSelect from "../components/MesPeProcessTreeSelect";
import { postAction, getAction, deleteAction } from "@/api/manage";

export default {
  name: "MesPeProcessMaterialBasisModal",
  mixins: [JEditableTableMixin],
  components: {
    JDictSelectTag,
    MesPeProcessTreeSelect,
  },
  data() {
    return {
      treeData: [
        { id: 1, pId: 0, value: 1, title: "顶级节点", processlayer: 0 },
      ],
      pidProcesslayerFlag: "",
      processlayer: "",
      processlayerArr: [],
      testVal: 1,
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 16,
      },
      labelCol2: {
        span: 3,
      },
      wrapperCol2: {
        span: 20,
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        processmcode: {
          rules: [{ required: true, message: "请输入工序编码!" }],
        },
        processmname: {
          rules: [{ required: true, message: "请输入工序名称!" }],
        },
        processsprc: {
          rules: [{ required: true, message: "请输入工序描述!" }],
        },
        processlayer: {
          rules: [{ required: true, message: "请输入工序层级!" }],
        },
        pid: { rules: [{ required: true, message: "请输入父级工序!" }] },
        productoffset: { rules: [{ required: true, message: "请输入偏置期!" }] },
      },
      refKeys: ["mesPeProductProcessRoute"],
      tableKeys: ["mesPeProductProcessRoute"],
      activeKey: "mesPeProductProcessRoute",
      // 基础信息工艺路线
      mesPeProductProcessRouteTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: "产品系列",
            key: "productLine",
            type: FormTypes.input,
            width: "200px",
            placeholder: "请输入${title}",
            defaultValue: "",
            validateRules: [{ required: true, message: "${title}不能为空" }],
          },
          {
            title: "工艺路线内码",
            key: "processid",
            type: FormTypes.input,
            width: "200px",
            placeholder: "请输入${title}",
            defaultValue: "",
          },
          {
            title: "工艺路线编码",
            key: "processCoding",
            type: FormTypes.input,
            width: "200px",
            placeholder: "请输入${title}",
            defaultValue: "",
            validateRules: [{ required: true, message: "${title}不能为空" }],
          },
          {
            title: "工艺路线名称",
            key: "processName",
            type: FormTypes.input,
            width: "200px",
            placeholder: "请输入${title}",
            defaultValue: "",
            validateRules: [{ required: true, message: "${title}不能为空" }],
          },
          {
            title: "工艺路线类型",
            key: "processType",
            type: FormTypes.select,
            dictCode: "",
            width: "200px",
            placeholder: "请输入${title}",
            defaultValue: "",
            validateRules: [{ required: true, message: "${title}不能为空" }],
          },
        ],
      },
      url: {
        add: "/mes-craft/craft/mesPeDefinition/add",
        edit: "/mes-craft/craft/mesPeDefinition/edit",
        pid: "/mes-craft/craft/mesPeDefinition/getParentByDefinitionLayer",
        childList: "/mes-craft/craft/mesPeDefinition/child",
        mesPeProductProcessRoute: {
          list: "/mes-craft/craft/mesPeDefinition/queryByDefinitionId",
        },
      },
    };
  },

  methods: {
    onLoadData(treeNode) {
      return new Promise((resolve) => {
        const { id } = treeNode.dataRef;
        const params = {
          pid: id,
        };
        getAction(this.url.childList, params).then((res) => {
          console.log(res);
          if (res.data.length > 0) {
            res.data.forEach((ele) => {
              this.treeData.push({
                id: ele.id,
                pId: ele.pid,
                value: ele.id,
                title:  ele.processmcode + ' ' + ele.processmname,
                isLeaf: !ele.hasChild,
                processlayer: ele.processlayer,
                disabled: ele.processlayer >= 3,
              });
            });
            resolve();
          }
        });
      });
    },

    processlayerChange(val) {
      this.processlayerFlag = val;
    },

    pidChange(val, label, extra) {
      this.pidProcesslayerFlag = extra.triggerNode.dataRef.processlayer;
      let processlayer = this.pidProcesslayerFlag * 1 + 1 + "";
      this.processlayer = processlayer
      this.form.setFieldsValue({processlayer})
    },

    handleOk() {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let httpurl = "";
          let method = "";
          this.model.processlayer = this.processlayer
          let formData = Object.assign(this.model, values);
          this.formData = Object.assign(this.model, values);
          //新增触发
          if (!this.model.id) {
            httpurl += this.url.add;
            method = "post";
            if (this.EnhanceJS.afterAdd) {
              //新增之前
              let Obj = eval(this.EnhanceJS.afterAdd);
              new Obj(this);
            } else {
              console.log("表单提交数据", formData);
              formData.state = 0
              that.modalFrom(httpurl, formData, method);
            }
          } else {
            //编辑触发
            httpurl += this.url.edit;
            method = "put";
            if (this.EnhanceJS.afterEdit) {
              //编辑之前
              let Obj = eval(this.EnhanceJS.afterEdit);
              new Obj(this);
            } else {
              console.log("表单提交数据", formData);
              that.modalFrom(httpurl, formData, method);
            }
          }
        }
      });
    },

    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key));
      return Promise.all(values);
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      let fieldval = pick(
        this.model,
        "processmcode",
        "processmname",
        "processsprc",
        "processlayer",
        "pid",
        "productoffset",
        "distribution"
      );
      this.processlayer = this.model.processlayer
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval);
      });
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id };
        this.requestSubTableData(
          this.url.mesPeProductProcessRoute.list,
          params,
          this.mesPeProductProcessRouteTable
        );
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue);
      return {
        ...main, // 展开
        mesPeProductProcessRouteList: allValues.tablesValue[0].values,
      };
    },
    /** 关闭弹窗，并将所有JEditableTable实例回归到初始状态 */
    close () {
      this.visible = false
      this.eachAllTable((item) => {
        item.initialize()
      })
      this.$emit('close')
      this.processlayer = ''
    },    
    validateError(msg) {
      this.$message.error(msg);
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          "processmcode",
          "processmname",
          "processsprc",
          "processlayer",
          "pid",
          "productoffset",
          "distribution"
        )
      );
    },
  },
};
</script>

<style scoped>
</style>